#! /usr/bin/env python
# -*- coding: utf-8 -*-

from django import forms
from web.form.bootstrap import BootStrap
from web import models
from django.core.exceptions import ValidationError
from utils.tencent.cos import check_file


class FolderModelForm(BootStrap, forms.ModelForm):

    class Meta:
        model = models.FileRepository
        fields = ['name']

    def __init__(self, request, parent_object, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request
        self.parent_obj = parent_object

    def clean_name(self):
        name = self.cleaned_data['name']

        # 判断当前目录下此文件夹是否存在
        if self.parent_obj:
            exist = models.FileRepository.objects.filter(file_type=2, name=name, project=self.request.tracer.project,
                                                         parent=self.parent_obj).exists()
        else:
            exist = models.FileRepository.objects.filter(file_type=2, name=name, project=self.request.tracer.project,
                                                         parent__isnull=True).exists()

        if exist:
            raise ValidationError('文件夹已存在')

        return name


class FileModelForm(forms.ModelForm):
    etag = forms.CharField(label='ETag')

    class Meta:
        model = models.FileRepository
        exclude = ['project', 'file_type', 'update_user', 'update_datetime']

    def clean_file_path(self):
        return "https://{}".format(self.cleaned_data['file_path'])

    ''' 验证数据
    def clean(self):
        key = self.cleaned_data.get('key')
        etag = self.cleaned_data.get('etag')

        if not key or not etag:
            return self.cleaned_data

        # 向cos校验文件
        from qcloud_cos.cos_exception import CosServiceError
        try:
            response = check_file(
                self.resquest.tracer.project.bucket, key, self.response.tracer.project.region
            )
            print(response)
        except CosServiceError as e:
            self.add_error('key', '文件不存在')
            return self.cleaned_data

        cos_etag = response.get('ETag')
        if etag != cos_etag:
            self.add_error('etag', 'ETag 错误')
            return self.cleaned_data

        return self.cleaned_data
    '''


